package com.itmuch.cloud.study.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.itmuch.cloud.study.entity.JwtUser;
import com.itmuch.cloud.study.service.JwtUserDetailsService;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService,JwtUserDetailsService {
//    @Autowired
//    private UserRepository userRepository;

	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	String sql = "select * from t_user where userName='"+username+"'";
    	List<JwtUser> users1 = null;
    	
    	try {
			users1= jdbcTemplate.query(sql, new RowMapper<JwtUser>() {
				
				@Override
				public JwtUser mapRow(ResultSet rs, int rowNum) throws SQLException {
					// TODO Auto-generated method stub
					JwtUser user = new JwtUser();
					user.setUsername(rs.getString("userName"));
					user.setPassword(rs.getString("passWord"));
					return user;
				}
			});
			
		} catch (Exception e) {
			// TODO: handle exception
			throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
		}
    	if(users1 == null || users1.size()==0){
    	//	throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
    		
    		return null;
    		
    		
    	}else{
    		//return new JwtUser(username);
    		return users1.get(0);
    	}
    }
    @Override
   public List<JwtUser> findByUserName(String userName,String passWord){
		String sql = "select * from t_user where userName='"+userName+"' and passWord='"+passWord+"'";
		List<JwtUser> users1 = null;
		try {
			users1= jdbcTemplate.query(sql, new RowMapper<JwtUser>() {
				
				@Override
				public JwtUser mapRow(ResultSet rs, int rowNum) throws SQLException {
					// TODO Auto-generated method stub
					JwtUser user = new JwtUser(rs.getString("userName"));
					return user;
				}
			});
			
		} catch (Exception e) {
			// TODO: handle exception
			return users1;
		}
		return users1;
	}
	
}
